package com.sunwhite.herostore.config.mq;

import com.alibaba.fastjson.JSONObject;
import com.sunwhite.herostore.config.RedisUtil;
import com.sunwhite.herostore.service.RankService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class MQConsumer {

    /**
     * 日志对象
     */
    static private final Logger log = LoggerFactory.getLogger(MQConsumer.class);

    /**
     * 私有化类默认构造器
     */
    private MQConsumer() {
    }

    /**
     * 初始化
     */
    public static  void init(){
        //创建队列消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("herostore");
        //设置nameserver 地址
        consumer.setNamesrvAddr("119.3.228.251:9876");

        try {
            consumer.subscribe("Victor","*");

            //注册回调
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgExtList, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    for (MessageExt messageExt : msgExtList) {
                        //解析战斗结果
                        VictorMsg victorMsg = JSONObject.parseObject(messageExt.getBody(), VictorMsg.class);

                        log.info("从消息队列中获取战斗结果，winnerId={},loserId={}",victorMsg.winnerId,victorMsg.loserId);

                        //刷新排行榜
                        RankService.getInstance().refreshRank(victorMsg.winnerId,victorMsg.loserId);
                    }

                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });

            //启动消费者
            consumer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
